package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.commons.templates.HuanXinTemplate;
import com.tanhua.domain.db.BlackList;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.UserLike;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.RecommendUserQueryParam;
import com.tanhua.domain.vo.TodayBestVo;
import com.tanhua.dubbo.api.db.BlackListApi;
import com.tanhua.dubbo.api.db.QuestionApi;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.dubbo.api.mongo.UserLikeApi;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 今日佳人业务处理层
 */
@Service
@Slf4j
public class TodayBestService {

    @Reference
    private RecommendUserApi recommendUserApi;

    @Reference
    private UserInfoApi userInfoApi;


    @Reference
    private QuestionApi questionApi;


    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Reference
    private UserLikeApi userLikeApi;

    @Reference
    private FriendApi friendApi;

    @Reference
    private BlackListApi blackListApi;
    /**
     * 首页-今日佳人
     */
    public TodayBestVo todayBest() {
        Long toUserId = UserHolder.getUserId();//当前登录用户id
        //a.根据当前用户id 查询一条今日佳人数据（调用服务提供者） -- recommend_user
        RecommendUser recommendUser = recommendUserApi.queryMaxScoreByToUserId(toUserId);
        //b.如果今日佳人数据不存在，则设置一条默认假数据（为了提升用户体验）
        if (recommendUser == null) {
            //默认数据
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1l);
            recommendUser.setScore(99d);
        }
        //c.根据佳人用户id调用服务查询佳人用户信息 tb_userInfo
        Long userId = recommendUser.getUserId();//佳人用户id
        UserInfo userInfo = userInfoApi.queryUserInfo(userId);
        //d.根据以上调用服务结果封装Vo返回
        TodayBestVo todayBestVo = new TodayBestVo();
        BeanUtils.copyProperties(userInfo, todayBestVo);
        //设置tags
        if (!StringUtils.isEmpty(userInfo.getTags())) {
            todayBestVo.setTags(userInfo.getTags().split(","));
        }
        //设置缘分值
        todayBestVo.setFateValue(recommendUser.getScore().longValue());
        return todayBestVo;
    }

    /**
     * 首页-佳人列表数据分页查询
     */
    public PageResult<TodayBestVo> recommendation(RecommendUserQueryParam param) {
        //定义返回PageResultVo
        PageResult<TodayBestVo> voPageResult = new PageResult<>();

        Long currentUserId = UserHolder.getUserId();
        //1.跟当前登录用户id 分页参数 分页查询佳人列表数据
        PageResult<RecommendUser> pageResult = recommendUserApi.queryPageByUserId(param.getPage(), param.getPagesize(), currentUserId);
        //2.如果数据为空，设置默认数据
        List<RecommendUser> recommendUserList = new ArrayList<>();
        if (pageResult == null || CollectionUtils.isEmpty(pageResult.getItems())) {
            recommendUserList = defaultRecommend();
        } else {
            recommendUserList = pageResult.getItems();
        }
        //3.根据userId查询userInfo
        //4.将List<RecommendUser>转为List<TodayBestVo>
        List<TodayBestVo> todayBestVoList = new ArrayList<>();
        for (RecommendUser recommendUser : recommendUserList) {
            //根据以上调用服务结果封装Vo返回
            TodayBestVo todayBestVo = new TodayBestVo();
            Long userId = recommendUser.getUserId();//佳人用户id
            UserInfo userInfo = userInfoApi.queryUserInfo(userId);
            BeanUtils.copyProperties(userInfo, todayBestVo);
            //设置tags
            if (!StringUtils.isEmpty(userInfo.getTags())) {
                todayBestVo.setTags(userInfo.getTags().split(","));
            }
            //设置缘分值
            todayBestVo.setFateValue(recommendUser.getScore().longValue());
            todayBestVoList.add(todayBestVo);
        }
        //4.将数据封装返回
        BeanUtils.copyProperties(pageResult, voPageResult);//copy分页数据
        voPageResult.setItems(todayBestVoList);//将todayBestVoList设置到返回的Vo中
        return voPageResult;
    }


    //构造默认数据
    private List<RecommendUser> defaultRecommend() {
        String ids = "1,2,3,4,5,6,7,8,9,10";
        List<RecommendUser> records = new ArrayList<>();
        for (String id : ids.split(",")) {
            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setUserId(Long.valueOf(id));
            recommendUser.setScore(RandomUtils.nextDouble(70, 98));
            records.add(recommendUser);
        }
        return records;
    }

    /**
     * 查看用户详情
     * {id}：佳人用户id
     */
    public TodayBestVo personalInfo(Long personUserId) {

        // a.根据佳人用户id查询userInfo
        UserInfo userInfo = userInfoApi.queryUserInfo(personUserId);
        //  b.调用服务获取缘分值
        Double score = recommendUserApi.queryForScore(personUserId, UserHolder.getUserId());
        //  c.封装vo
        TodayBestVo vo = new TodayBestVo();
        BeanUtils.copyProperties(userInfo, vo);
        if (userInfo != null && !StringUtils.isEmpty(userInfo.getTags())) {
            vo.setTags(userInfo.getTags().split(","));
        }
        vo.setFateValue(score.longValue());//缘分值
        return vo;

    }

    /**
     * 查询陌生人问题
     * userId:佳人用户id
     */
    public String strangerQuestions(Long userId) {
        String txt = "约吗？";
        Question question = questionApi.queryByUserId(userId);
        if (question != null && !StringUtils.isEmpty(question.getTxt())) {
            txt = question.getTxt();
        }
        return txt;
    }

    /**
     * 回复陌生人问题
     */
    public void replyStrangerQuestions(Long userId, String reply) {
        //a.UserHolder.getuserId()获取当前用户id
        Long currentUserId = UserHolder.getUserId();//当前用户id
        //b.根据当前登录用户id 查询userInfo 获取昵称
        UserInfo userInfo = userInfoApi.queryUserInfo(currentUserId);
        String nickname = userInfo.getNickname();

        //c.根据佳人用户id查询问题
        Question question = questionApi.queryByUserId(userId);
        String txt = "约吗？";
        if(question != null && !StringUtils.isEmpty(question.getTxt())){
            txt = question.getTxt();
        }
        //d.将以上数据封装Map 并将Map转为String字符串
        Map<String,String> map = new HashMap();
        map.put("userId",currentUserId.toString());//当前用户id
        map.put("nickname",nickname);//当前用户昵称
        map.put("strangerQuestion",txt);//佳人问题
        map.put("reply",reply);//当前用户的回复
        String message = JSON.toJSONString(map); //将map转为message消息
        //e.调用环信云发送消息给userId佳人用户id target：佳人用户id msg:消息内容
        huanXinTemplate.sendMsg(userId.toString(),message);
        log.debug("用户{}发送消息给用户{},内容是{}",currentUserId,userId,message);
    }

    /**
     * 探花-喜欢
     */
    public void love(Long id) {
        Long userId = UserHolder.getUserId();//当前用户id
        //1.根据当前用户id 与 好友id 删除UserLike中 粉丝-喜欢记录
        //userLikeApi.deleteById(userId, id);
        //1.喜欢插入信息到user_like表中
        UserLike userLike = new UserLike();
        userLike.setId(ObjectId.get());//主键id
        userLike.setUserId(userId);//用户id，自己
        userLike.setLikeUserId(id);//喜欢的用户id，对方
        userLike.setCreated(System.currentTimeMillis()); //创建时间

        //2.保存喜欢信息并根据用户id查询是否相互喜欢
        UserLike userLike1 = userLikeApi.saveQuery(userLike);

        if (userLike1 != null) {
            //2.往好友表tanhua_users表中保存2条记录
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(id);
            friendApi.saveFriend(friend);
            //3.调用环信交友方法
            huanXinTemplate.makeFriends(userId, id);
        }
    }

    /**
     * 探花-不喜欢 加入黑名单
     */
    public void unLove(Long id) {
        Long userId = UserHolder.getUserId();
        //1.不喜欢 插入不喜欢信息到user_like表中
        BlackList blackList = new BlackList();
        blackList.setUserId(userId);
        blackList.setBlackUserId(id);
        blackListApi.save(blackList);
    }
}
